package models

import (
	"time"

	"gorm.io/gorm"
)

type Role struct {
	ID          uint      `json:"id" gorm:"primaryKey"`
	Name        string    `json:"name" gorm:"type:varchar(50);uniqueIndex;not null"`
	DisplayName string    `json:"display_name" gorm:"type:varchar(100);not null"`
	Description string    `json:"description" gorm:"type:text"`
	IsActive    bool      `json:"is_active" gorm:"default:true"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联关系
	UserRoles       []UserRole       `json:"user_roles" gorm:"foreignKey:RoleID"`
	Users           []User           `json:"users" gorm:"many2many:user_roles;"`
	RolePermissions []RolePermission `json:"role_permissions" gorm:"foreignKey:RoleID"`
	Permissions     []Permission     `json:"permissions" gorm:"many2many:role_permissions;"`
}

// TableName 指定表名
func (Role) TableName() string {
	return "roles"
}

// HasPermission 检查角色是否拥有指定权限
func (r *Role) HasPermission(permissionName string) bool {
	for _, permission := range r.Permissions {
		if permission.Name == permissionName {
			return true
		}
	}
	return false
}